package com.live.stamp.web.im.service.impl;

import com.alibaba.fastjson.JSON;
import com.live.stamp.base.service.impl.BaseSupportServiceImpl;
import com.live.stamp.base.token.UserModelUtil;
import com.live.stamp.base.utils.HttpClientUtil;
import com.live.stamp.web.im.service.ImService;
import com.live.stamp.web.user.model.TUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.container.core.common.BusinessException;
import org.springframework.boot.container.core.log.ZKLogger;
import org.springframework.boot.container.core.log.ZKLoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cwd E-mail: wendong.cao@jsxfedu.com
 * @version 1
 * @date 2018/4/20 10:05
 */
@Service
public class ImServiceImpl extends BaseSupportServiceImpl implements ImService {
    private static final ZKLogger logger = ZKLoggerFactory.getLogger(ImServiceImpl.class);

    @Value("${im.appKey}")
    private String appKey;
    @Value("${im.appSecret}")
    private String appSecret;
    @Value("${im.url}")
    private String url;

    @Override
    public Map<String, Object> getImToken() throws BusinessException {
        logger.info("enter getImToken method");

        TUser tUser = UserModelUtil.getUserModel();
        if(tUser == null) {
            throw new BusinessException("获取im token失败，用户信息为空");
        }

        String reqImTokenApi = reqImTokenApi(tUser);
        if(reqImTokenApi != null) {
            return (Map<String, Object>) JSON.parse(reqImTokenApi);
        }

        return null;
    }

    /**
     * 请求im token api
     * @return
     */
    public String reqImTokenApi(TUser tUser) {

        Map<String, String> params = new HashMap<>();
        params.put("userId", tUser.getId());
        params.put("name", tUser.getUserName());
        params.put("portraitUri", tUser.getPhotoUrl());

        Map<String, String> header = createImHttpHeader();

        return HttpClientUtil.doPost(url, header, params);
    }

    /**
     * 生成im 请求头
     * @return
     */
    public Map<String, String> createImHttpHeader() {
        Map<String, String> reslut = new HashMap<>();
        int rand = RandomUtils.nextInt(1000, 9999);         //随机数
        Date now = new Date();                              //当前时间
        String Signature = DigestUtils.shaHex(appSecret+rand+now.getTime());

        reslut.put("App-Key", appKey);
        reslut.put("Nonce", ""+rand);
        reslut.put("Timestamp", ""+now.getTime());
        reslut.put("Signature", Signature);
        return reslut;
    }

}
